package com.example.zzj.ziwuyundemo.activity;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.zzj.ziwuyundemo.R;
import com.example.zzj.ziwuyundemo.adapter.DiverRecyclerAdapter;
import com.example.zzj.ziwuyundemo.adapter.SuperCarAdapter;
import com.example.zzj.ziwuyundemo.base.BaseActivity;
import com.example.zzj.ziwuyundemo.entity.DetailEntity;
import com.example.zzj.ziwuyundemo.entity.DetailOrEntity;
import com.example.zzj.ziwuyundemo.entity.DriverEntity;
import com.example.zzj.ziwuyundemo.entity.SupercargoEntity;
import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;


/**
 * 详情
 * Created by zzj on 2016/12/16.
 */

public class DetailActivity extends BaseActivity implements View.OnClickListener {
    @InjectView(R.id.back)
    ImageView back;
    @InjectView(R.id.name_detail)
    TextView nameDetail;
    @InjectView(R.id.img_info)
    ImageView imgInfo;
    @InjectView(R.id.planCode)
    TextView planCode;
    @InjectView(R.id.createDate)
    TextView createDate;
    @InjectView(R.id.carrierVehicle)
    TextView carrierVehicle;
    @InjectView(R.id.supplier)
    TextView supplier;
    @InjectView(R.id.goods)
    TextView goods;
    @InjectView(R.id.goodsCategory)
    TextView goodsCategory;
    @InjectView(R.id.transportRoutes)
    TextView transportRoutes;
    //    @InjectView(R.id.recycler)
//    RecyclerView recycler;
//    @InjectView(R.id.recyclerView)
//    RecyclerView recyclerView;
    @InjectView(R.id.refuse)
    Button refuse;
    @InjectView(R.id.reply)
    Button reply;
    @InjectView(R.id.noReply)
    TextView noReply;
    @InjectView(R.id.driver_allocation)
    Button driverAllocation;
    @InjectView(R.id.driver_name)
    TextView driverName;
    @InjectView(R.id.driver_phone)
    TextView driverPhone;
    @InjectView(R.id.supercargo_allocation)
    Button supercargoAllocation;
    @InjectView(R.id.supercargo_name)
    TextView supercargoName;
    @InjectView(R.id.supercargo_phone)
    TextView supercargoPhone;
    @InjectView(R.id.driver_relative)
    RelativeLayout driverRelative;
    @InjectView(R.id.supercargo_relative)
    RelativeLayout supercargoRelative;


    private Intent intent;
    private String pcId;
    private String carrierVehicle2;
    private String transportRoutes2;
    private String supplier2;
    private String goods2;
    private String goodsCategory2;
    private String planCode2;
    private String createDate2;
    private String status2;
    private String carrierPlansId;
    private String diverId;
    private String diversName;
    private String diversPhone;
    private String superCarId;
    private String superCarsName;
    private String superCarsPhone;
    private OkHttpClient okHttpClient;
    private DriverEntity driverEntity;//驾驶员实体类
    private SupercargoEntity supercargoEntity;//押运员实体类
    private DetailEntity detailEntity;
    private DetailOrEntity detailOrEntity;
    private DiverRecyclerAdapter diverRecyclerAdapter;
    private SuperCarAdapter superCarAdapter;
    private List<DriverEntity.DriverpageBean> driverpageBeen = new ArrayList<>();
    private List<SupercargoEntity.PersonSupercargoBean> personSupercargoBeen = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail);
        ButterKnife.inject(this);
        okHttpClient = new OkHttpClient();
        initView();
        initData();
    }

    private void initData() {
        back.setOnClickListener(this);
        reply.setOnClickListener(this);
        refuse.setOnClickListener(this);
        driverAllocation.setOnClickListener(this);
        supercargoAllocation.setOnClickListener(this);
    }

    private void initView() {
        back.setVisibility(View.VISIBLE);
        nameDetail.setVisibility(View.VISIBLE);
        imgInfo.setVisibility(View.VISIBLE);
        intent = getIntent();
        pcId = intent.getStringExtra("pcId");
        carrierVehicle2 = intent.getStringExtra("carrierVehicle");//车牌
        transportRoutes2 = intent.getStringExtra("transportRoutes");//行驶路线
        supplier2 = intent.getStringExtra("supplier");//收货商
        goods2 = intent.getStringExtra("goods");//货物
        goodsCategory2 = intent.getStringExtra("goodsCategory");//货物类别
        planCode2 = intent.getStringExtra("planCode");//运单号
        createDate2 = intent.getStringExtra("createDate");//时间
        status2 = intent.getStringExtra("status");
        carrierPlansId = intent.getStringExtra("carrierPlansId");

        carrierVehicle.setText(carrierVehicle2);
        transportRoutes.setText(transportRoutes2);
        supplier.setText(supplier2);
        goods.setText(goods2);
        goodsCategory.setText(goodsCategory2);
        planCode.setText(planCode2);
        createDate.setText(createDate2);


        switch (status2) {
            case "0":
                noReply.setText("未响应");
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.driver_allocation:
                LayoutInflater inflater = getLayoutInflater();
                final View view = inflater.inflate(R.layout.driver_dialog, null);
//                EditText editText = (EditText) view.findViewById(R.id.search);
                final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.driver_recycler);
                //创建对象框
                final AlertDialog.Builder builderDialog = new AlertDialog.Builder(mContext);
                builderDialog.setView(view);
                //设置常用api，并show弹出
                builderDialog.setCancelable(true);    //设置按钮是否可以按返回键取消,false则不可以取消
                final AlertDialog dialog = builderDialog.create();    //创建对话框

                FormEncodingBuilder builder = new FormEncodingBuilder();
                builder.add("pcId", pcId);
                Log.d("pcId", pcId);
                final Request request = new Request.Builder()
                        .url("http://192.168.1.75:8080/mclcm/a/mclcm/test/getPerson")
                        .post(builder.build())
                        .build();
                Log.d("request2", request.toString());
                okHttpClient.newCall(request).enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {

                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        String driverBody = response.body().string();
                        Log.d("driverBody", driverBody);
                        Gson gson = new Gson();
                        driverEntity = new DriverEntity();
                        driverEntity = gson.fromJson(driverBody, DriverEntity.class);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
//                                if (diverRecyclerAdapter == null){
                                driverpageBeen.addAll(driverEntity.getDriverpage());
                                Log.d("zzz",driverpageBeen.toString());
                                recyclerView.setLayoutManager(new LinearLayoutManager(mContext));
                                diverRecyclerAdapter = new DiverRecyclerAdapter(mContext, driverpageBeen);
                                recyclerView.setAdapter(diverRecyclerAdapter);

//                                }else {
//                                    recyclerView.removeAllViews();
//                                diverRecyclerAdapter.notifyDataSetChanged();
//                                    diverRecyclerAdapter.addDiver(driverEntity.getDriverpage());
//                                    Log.d("driverpage",driverEntity.getDriverpage().toString());
//                                    diverRecyclerAdapter.notifyDataSetChanged();
//                                }

                                diverRecyclerAdapter.setOnItemClickListener(new DiverRecyclerAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(View view, int position) {
                                        diverId = driverEntity.getDriverpage().get(position).getId();
                                        diversName = driverpageBeen.get(position).getName();
                                        diversPhone = driverpageBeen.get(position).getPhoneNumbChief();
                                        dialog.cancel();
                                        driverRelative.setVisibility(View.VISIBLE);
                                        driverName.setText(diversName);
                                        driverPhone.setText(diversPhone);
                                    }
                                });
                            }
                        });
                    }
                });
                dialog.setCanceledOnTouchOutside(false);    //设置弹出框失去焦点是否隐藏,即点击屏蔽其它地方是否隐藏
                dialog.show();
                break;
            case R.id.supercargo_allocation:
                LayoutInflater inflater2 = getLayoutInflater();
                final View view2 = inflater2.inflate(R.layout.driver_dialog, null);
//                EditText editText = (EditText) view.findViewById(R.id.search);
                final RecyclerView recyclerView2 = (RecyclerView) view2.findViewById(R.id.driver_recycler);
                //创建对象框
                final AlertDialog.Builder builderDialog2 = new AlertDialog.Builder(mContext);
                builderDialog2.setView(view2);
                //设置常用api，并show弹出
                builderDialog2.setCancelable(true);    //设置按钮是否可以按返回键取消,false则不可以取消
                final AlertDialog dialog2 = builderDialog2.create();    //创建对话框

                FormEncodingBuilder builder2 = new FormEncodingBuilder();
                builder2.add("pcId", pcId);
                Log.d("pcId", pcId);
                final Request request2 = new Request.Builder()
                        .url("http://192.168.1.75:8080/mclcm/a/mclcm/test/getPerson1")
                        .post(builder2.build())
                        .build();
                Log.d("request2", request2.toString());
                okHttpClient.newCall(request2).enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {

                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        String superCarGoBody = response.body().string();
                        Log.d("superCarGoBody", superCarGoBody);
                        Gson gson = new Gson();
                        supercargoEntity = new SupercargoEntity();
                        supercargoEntity = gson.fromJson(superCarGoBody,SupercargoEntity.class);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                personSupercargoBeen.addAll(supercargoEntity.getPerson_supercargo());
                                recyclerView2.setLayoutManager(new LinearLayoutManager(mContext));
                                superCarAdapter = new SuperCarAdapter(mContext, personSupercargoBeen);
                                recyclerView2.setAdapter(superCarAdapter);
                                superCarAdapter.setOnItemClickListener(new SuperCarAdapter.OnItemClickListener() {
                                    @Override
                                    public void onItemClick(View view, int position) {
                                        superCarId = supercargoEntity.getPerson_supercargo().get(position).getId();
                                        superCarsName = supercargoEntity.getPerson_supercargo().get(position).getName();
                                        superCarsPhone = supercargoEntity.getPerson_supercargo().get(position).getPhoneNumbChief();
                                        dialog2.cancel();
                                        supercargoRelative.setVisibility(View.VISIBLE);
                                        supercargoName.setText(superCarsName);
                                        supercargoPhone.setText(superCarsPhone);
                                    }
                                });
                            }
                        });
                    }
                });
                dialog2.setCanceledOnTouchOutside(false);    //设置弹出框失去焦点是否隐藏,即点击屏蔽其它地方是否隐藏
                dialog2.show();
                break;
            case R.id.reply:
                FormEncodingBuilder builder3 = new FormEncodingBuilder();
                builder3.add("pcId", pcId);
                builder3.add("driverId", diverId);
                Log.d("dId", diverId);
                builder3.add("supercargoId", superCarId);
                Log.d("dId", superCarId);

                final Request request3 = new Request.Builder()
                        .url("http://192.168.1.75:8080/mclcm/a/mclcm/test/responsePcd")
                        .post(builder3.build())
                        .build();
                okHttpClient.newCall(request3).enqueue(new Callback() {
                    @Override
                    public void onFailure(Request request, IOException e) {

                    }

                    @Override
                    public void onResponse(Response response) throws IOException {
                        String replyBody = response.body().string();
                        Log.d("request3", replyBody);
                        if (replyBody.equals("")) {
                            Toast.makeText(mContext, "服务请求异常！", Toast.LENGTH_SHORT).show();
                        } else {
                            Gson gson = new Gson();
                            detailOrEntity = new DetailOrEntity();
                            detailOrEntity = gson.fromJson(replyBody, DetailOrEntity.class);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (detailOrEntity.getIsLogin().equals("success")) {
                                        finish();
                                    } else {
                                        Toast.makeText(mContext, "响应失败，请重试！", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            });
                        }
                    }
                });
                break;
            case R.id.refuse:
                LayoutInflater inflater4 = getLayoutInflater();
                final View view4 = inflater4.inflate(R.layout.reason_dialog, null);
                final EditText editText = (EditText) view4.findViewById(R.id.textNot);
                TextView textView = (TextView) view4.findViewById(R.id.date);
                //创建对象框
                final AlertDialog.Builder builderDialog4 = new AlertDialog.Builder(mContext);
                builderDialog4.setTitle("拒绝理由");    //设置对话框标题
                builderDialog4.setIcon(android.R.drawable.ic_dialog_info);    //设置对话框标题前的图标
                builderDialog4.setView(view4);
                SimpleDateFormat formatter = new SimpleDateFormat ("yyyy-MM-dd HH:mm:ss");
                Date curDate = new Date(System.currentTimeMillis());//获取当前时间
                final String strDate = formatter.format(curDate);
                textView.setText(strDate);
                //将输入框赋值给Dialog,并增加确定取消按键
                builderDialog4.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String et = editText.getText().toString();
                        Toast.makeText(mContext, "你输入的是: " + editText.getText().toString(), Toast.LENGTH_SHORT).show();
                        FormEncodingBuilder builder = new FormEncodingBuilder();
                        builder.add("pcId", pcId);
                        builder.add("response",et);
                        builder.add("cyId",carrierPlansId);
                        builder.add("time",strDate);
                        final Request request = new Request.Builder()
                                .url("http://192.168.1.75:8080/mclcm/a/mclcm/test/Refused")
                                .post(builder.build())
                                .build();
                        okHttpClient.newCall(request).enqueue(new Callback() {
                            @Override
                            public void onFailure(Request request, IOException e) {

                            }

                            @Override
                            public void onResponse(Response response) throws IOException {
                                String responseBody = response.body().string();
                                Log.d("request4", responseBody);
                                Gson gson = new Gson();
                                detailOrEntity = new DetailOrEntity();
                                detailOrEntity = gson.fromJson(responseBody, DetailOrEntity.class);
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (detailOrEntity.getIsLogin().equals("success")) {
                                            Toast.makeText(mContext, "成功", Toast.LENGTH_SHORT).show();
                                            finish();
                                        } else {
                                            Toast.makeText(mContext, "拒绝失败，请重试！", Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                            }
                        });

                    }
                });
                builderDialog4.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });

                //设置常用api，并show弹出
                builderDialog4.setCancelable(true);    //设置按钮是否可以按返回键取消,false则不可以取消
                AlertDialog dialog4 = builderDialog4.create();    //创建对话框
                dialog4.setCanceledOnTouchOutside(false);    //设置弹出框失去焦点是否隐藏,即点击屏蔽其它地方是否隐藏
                dialog4.show();
                break;
        }
    }

}
